package com.cupster.android_x_frame;


import android.Manifest.permission;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 *  Encoding by Cupster on 2019/12/24 16:27.
 *
 * 动态申请权限工具类
 */
public final class PermissionUtil {

    public static final String[] GROUP_CALENDAR      = {
            permission.READ_CALENDAR, permission.WRITE_CALENDAR
    };
    public static final String[] GROUP_CAMERA        = {
            permission.CAMERA
    };
    public static final String[] GROUP_CONTACTS      = {
            permission.READ_CONTACTS, permission.WRITE_CONTACTS, permission.GET_ACCOUNTS
    };
    public static final String[] GROUP_LOCATION      = {
            permission.ACCESS_FINE_LOCATION, permission.ACCESS_COARSE_LOCATION
    };
    public static final String[] GROUP_MICROPHONE    = {
            permission.RECORD_AUDIO
    };
    public static final String[] GROUP_PHONE         = {
            permission.READ_PHONE_STATE, permission.READ_PHONE_NUMBERS, permission.CALL_PHONE,
            permission.READ_CALL_LOG, permission.WRITE_CALL_LOG, permission.ADD_VOICEMAIL,
            permission.USE_SIP, permission.PROCESS_OUTGOING_CALLS, permission.ANSWER_PHONE_CALLS
    };
    public static final String[] GROUP_PHONE_BELOW_O = {
            permission.READ_PHONE_STATE, permission.READ_PHONE_NUMBERS, permission.CALL_PHONE,
            permission.READ_CALL_LOG, permission.WRITE_CALL_LOG, permission.ADD_VOICEMAIL,
            permission.USE_SIP, permission.PROCESS_OUTGOING_CALLS
    };
    public static final String[] GROUP_SENSORS       = {
            permission.BODY_SENSORS
    };
    public static final String[] GROUP_SMS           = {
            permission.SEND_SMS, permission.RECEIVE_SMS, permission.READ_SMS,
            permission.RECEIVE_WAP_PUSH, permission.RECEIVE_MMS,
    };
    public static final String[] GROUP_STORAGE       = {
            permission.READ_EXTERNAL_STORAGE, permission.WRITE_EXTERNAL_STORAGE,
    };


    /**
     * 申请所有权限
     * 调用后，activity中复写 onRequestPermissionsResult（）处理申请权限结果
     * PERMISSION_DENIED = -1;
     * PERMISSION_GRANTED = 0;
     * @param context activity
     * @param requestCode 请求码
     */
    public static void applyPermission(Activity context ,int requestCode ,String pkg) {
        if (needApply(context ,pkg)) {
            String[] allpermissions ={};
            try {
                allpermissions = context.getPackageManager().getPackageInfo(pkg, PackageManager.GET_PERMISSIONS)
                        .requestedPermissions;
            } catch (PackageManager.NameNotFoundException e) {
                Log.e( "permission","app has no request any permission" );
            }
            ActivityCompat.requestPermissions( context, allpermissions, requestCode);
        }
    }
    /**
     * 申请指定权限
     * 调用后，activity中复写 onRequestPermissionsResult（）处理申请权限结果
     * PERMISSION_DENIED = -1;
     * PERMISSION_GRANTED = 0;
     * @param context activity
     * @param permissions 指定的权限
     */
    public static void applySignPermission(Activity context,int requestCode ,String[] permissions ) {
        if (!checkPermissions(context ,permissions)) {
            ActivityCompat.requestPermissions( context, permissions, requestCode);
        }
    }

    public static boolean isGranted(final String... permissions) {
        for (String permission : permissions) {
            if (!isGranted(permission)) {
                return false;
            }
        }
        return true;
    }

    private static boolean isGranted(Context context ,final String permission) {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.M
                || PackageManager.PERMISSION_GRANTED
                == ContextCompat.checkSelfPermission(context.getApplicationContext(), permission);
    }

    /**
     * 判断是否有权限限制
     * @param context activity
     * @param pkg 包名
     * @return 是否需要申请放行权限
     */
    public static boolean needApply(Activity context ,String pkg ){
        boolean needApply = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] allPermissions ={};
            try {
                allPermissions = context.getPackageManager().getPackageInfo(pkg, PackageManager.GET_PERMISSIONS)
                        .requestedPermissions;
            } catch (PackageManager.NameNotFoundException e) {
                Log.e( "permission","app has no request any permission" );
            }
            for (String permission : allPermissions) {
                int checkPermission = ContextCompat.checkSelfPermission(context.getApplicationContext(),
                        permission);
                if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                    needApply = true;
                }
            }
        }
        return needApply;
    }

    /**
     * 检测权限是否授权
     * Activity.onRequestPermissionsResult（）中回调使用
     * @param permissions 权限数组
     * @return true 有权限   false 被拒绝
     */
    private static boolean checkPermissions(Context activity ,String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(activity, permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public static void skipPermissionSetting(Context context){
//        String sdk = android.os.Build.VERSION.SDK; // SDK号
//        String model = android.os.Build.MODEL; // 手机型号
//        String release = android.os.Build.VERSION.RELEASE; // android系统版本号
        String brand = Build.BRAND;//手机厂商
        if (TextUtils.equals(brand.toLowerCase(), "redmi") || TextUtils.equals(brand.toLowerCase(), "xiaomi")) {
            gotoMiuiPermission(context);//小米
        } else if (TextUtils.equals(brand.toLowerCase(), "meizu")) {
            gotoMeizuPermission(context);
        } else if (TextUtils.equals(brand.toLowerCase(), "huawei") || TextUtils.equals(brand.toLowerCase(), "honor")) {
            gotoHuaweiPermission(context);
        } else {
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }


    /**
     * 跳转到miui的权限管理页面
     */
    private static void gotoMiuiPermission(Context context) {
        try { // MIUI 8
            Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", context.getPackageName());
            context.startActivity(localIntent);
        } catch (Exception e) {
            try { // MIUI 5/6/7
                Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                localIntent.putExtra("extra_pkgname", context.getPackageName());
                context.startActivity(localIntent);
            } catch (Exception e1) { // 否则跳转到应用详情
                context.startActivity(getAppDetailSettingIntent(context));
            }
        }
    }

    /**
     * 跳转到魅族的权限管理系统
     */
    private static void gotoMeizuPermission(Context context) {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.putExtra("packageName", context.getPackageName());
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }

    /**
     * 华为的权限管理页面
     */
    private static void gotoHuaweiPermission(Context context) {
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");//华为权限管理
            intent.setComponent(comp);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            context.startActivity(getAppDetailSettingIntent(context));
        }

    }

    /**
     * 获取应用详情页面intent（如果找不到要跳转的界面，也可以先把用户引导到系统设置页面）
     *
     * @return Intent
     */
    private static Intent getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package",context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName",context.getPackageName());
        }
        return localIntent;
    }

    /**
     * Launch the application's details settings.
     */
    public static void launchAppDetailsSettings(Context context ,String pkg) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + pkg));
        if (!isIntentAvailable( context ,intent)) return;
        context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    private static boolean isIntentAvailable(Context context ,final Intent intent) {
        return context.getApplicationContext().getPackageManager()
                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
                .size() > 0;
    }

}
